package com.itheima.sfbx.insurance.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.sfbx.framework.commons.constant.basic.SuperConstant;
import com.itheima.sfbx.framework.commons.constant.insure.InsureConstant;
import com.itheima.sfbx.framework.commons.dto.basic.TreeItemVO;
import com.itheima.sfbx.framework.commons.dto.basic.TreeVO;
import com.itheima.sfbx.framework.commons.exception.ProjectException;
import com.itheima.sfbx.framework.commons.utils.BeanConv;
import com.itheima.sfbx.framework.commons.utils.EmptyUtil;
import com.itheima.sfbx.framework.commons.utils.NoProcessing;
import com.itheima.sfbx.insurance.dto.CategoryCoefficentVO;
import com.itheima.sfbx.insurance.dto.CategoryConditionVO;
import com.itheima.sfbx.insurance.dto.CategorySafeguardVO;
import com.itheima.sfbx.insurance.dto.CategoryVO;
import com.itheima.sfbx.insurance.enums.CategoryEnum;
import com.itheima.sfbx.insurance.mapper.CategoryMapper;
import com.itheima.sfbx.insurance.pojo.Category;
import com.itheima.sfbx.insurance.pojo.CategoryCoefficent;
import com.itheima.sfbx.insurance.pojo.CategoryCondition;
import com.itheima.sfbx.insurance.pojo.CategorySafeguard;
import com.itheima.sfbx.insurance.service.ICategoryCoefficentService;
import com.itheima.sfbx.insurance.service.ICategoryConditionService;
import com.itheima.sfbx.insurance.service.ICategorySafeguardService;
import com.itheima.sfbx.insurance.service.ICategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description：保险分类服务实现类
 */
@Slf4j
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Autowired
    ICategoryConditionService categoryConditionService;

    @Autowired
    ICategoryCoefficentService categoryCoefficentService;

    @Autowired
    ICategorySafeguardService categorySafeguardService;

    private LambdaQueryWrapper<Category> queryWrapper(CategoryVO categoryVO) {
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.eq(StrUtil.isNotBlank(categoryVO.getCategoryNo()), Category::getCategoryNo, categoryVO.getCategoryNo());
        lqw.eq(StrUtil.isNotBlank(categoryVO.getParentCategoryNo()), Category::getParentCategoryNo, categoryVO.getParentCategoryNo());
        lqw.like(StrUtil.isNotBlank(categoryVO.getCategoryName()), Category::getCategoryName, categoryVO.getCategoryName());
        lqw.eq(StrUtil.isNotBlank(categoryVO.getDataState()), Category::getDataState, categoryVO.getDataState());
        lqw.eq(StrUtil.isNotBlank(categoryVO.getCategoryType()), Category::getCategoryType, categoryVO.getCategoryType());
        lqw.eq(StrUtil.isNotBlank(categoryVO.getLeafNode()), Category::getLeafNode, categoryVO.getLeafNode());
        lqw.eq(StrUtil.isNotBlank(categoryVO.getShowIndex()), Category::getShowIndex, categoryVO.getShowIndex());
        return lqw;
    }

    private void buildVoList(List<CategoryVO> voList){
         //代码走到这说明不为空
        //批量查，先拿到category的关联项
        Set<String> noSet = voList.stream().map(CategoryVO::getCategoryNo).collect(Collectors.toSet());
         //处理condition
        List<CategoryCondition> conditionList = categoryConditionService.lambdaQuery()
                .in(CategoryCondition::getCategoryNo, noSet)
                .list();
        Map<String, List<CategoryCondition>> conditionMap = conditionList.stream().collect(Collectors.groupingBy(CategoryCondition::getCategoryNo));
        //处理coefficent
        List<CategoryCoefficent> coefficentList = categoryCoefficentService.lambdaQuery()
                .in(CategoryCoefficent::getCategoryNo, noSet)
                .list();
        Map<String, List<CategoryCoefficent>> coefficentMap = coefficentList.stream().collect(Collectors.groupingBy(CategoryCoefficent::getCategoryNo));
        //处理safeguard
        List<CategorySafeguard> safeguardList = categorySafeguardService.lambdaQuery()
                .in(CategorySafeguard::getCategoryNo, noSet)
                .list();
        Map<String, List<CategorySafeguard>> safeguardMap = safeguardList.stream().collect(Collectors.groupingBy(CategorySafeguard::getCategoryNo));
        for (CategoryVO vo : voList) {
            List<CategoryCondition> conditions = conditionMap.get(vo.getCategoryNo());
            vo.setCategoryConditionVOs(BeanConv.toBeanList(conditions, CategoryConditionVO.class));
            List<CategoryCoefficent> coefficents = coefficentMap.get(vo.getCategoryNo());
            vo.setCategoryCoefficentVOs(BeanConv.toBeanList(coefficents, CategoryCoefficentVO.class));
            List<CategorySafeguard> safeguards = safeguardMap.get(vo.getCategoryNo());
            vo.setCategorySafeguardVOs(BeanConv.toBeanList(safeguards, CategorySafeguardVO.class));
        }
    }

    @Override
    public Page<CategoryVO> findPage(CategoryVO categoryVO, int pageNum, int pageSize) {
        Page<Category> page = this.page(new Page<>(pageNum, pageSize), queryWrapper(categoryVO));
        Page<CategoryVO> voPage = BeanConv.toPage(page, CategoryVO.class);
        List<CategoryVO> voList = voPage.getRecords();
        if (CollUtil.isEmpty(voList)){
            return voPage;
        }
        buildVoList(voList);
        return voPage;
    }

    @Override
    @Transactional
    public CategoryVO save(CategoryVO categoryVO) {
        //TODO
        return null;
    }

    @Override
    @Transactional
    public Boolean update(CategoryVO categoryVO) {
        Category category = this.getById(categoryVO.getId());
        if (category == null) {
            throw new ProjectException(CategoryEnum.UPDATE_FAIL);
        }
        this.updateById(BeanConv.toBean(categoryVO, Category.class));
        //先全删
        categoryConditionService.deleteByCategoryNo(categoryVO.getCategoryNo());
        categoryCoefficentService.deleteByCategoryNo(categoryVO.getCategoryNo());
        categorySafeguardService.deleteByCategoryNo(categoryVO.getCategoryNo());
        //再新增
        List<CategoryConditionVO> categoryConditionVOs = categoryVO.getCategoryConditionVOs();
        if (CollUtil.isNotEmpty(categoryConditionVOs)){
            categoryConditionVOs.forEach(co->co.setCategoryNo(categoryVO.getCategoryNo()));
            categoryConditionService.saveBatch(BeanConv.toBeanList(categoryConditionVOs, CategoryCondition.class));
        }
        List<CategoryCoefficentVO> categoryCoefficentVOs = categoryVO.getCategoryCoefficentVOs();
        if (CollUtil.isNotEmpty(categoryCoefficentVOs)){
            categoryCoefficentVOs.forEach(cc->cc.setCategoryNo(categoryVO.getCategoryNo()));
            categoryCoefficentService.saveBatch(BeanConv.toBeanList(categoryCoefficentVOs, CategoryCoefficent.class));
        }
        List<CategorySafeguardVO> categorySafeguardVOs = categoryVO.getCategorySafeguardVOs();
        if (CollUtil.isNotEmpty(categorySafeguardVOs)){
            categoryCoefficentVOs.forEach(cs->cs.setCategoryNo(categoryVO.getCategoryNo()));
            categorySafeguardService.saveBatch(BeanConv.toBeanList(categorySafeguardVOs, CategorySafeguard.class));
        }
        return true;
    }

    @Override
    @Transactional
    public Boolean delete(String[] checkedIds) {
        //TODO
        return null;
    }

    @Override
    public List<CategoryVO> findList(CategoryVO categoryVO) {
       LambdaQueryWrapper<Category> lqw = queryWrapper(categoryVO);
        List<Category> list = this.list(lqw);
        List<CategoryVO> voList = BeanConv.toBeanList(list, CategoryVO.class);
        if(voList.isEmpty()){
            return new ArrayList<>();
        }
        List<Long> nodeFloors = categoryVO.getNodeFloors();
        if (CollUtil.isNotEmpty(nodeFloors)) {
            voList = voList.stream().filter(vo->{
                long level = NoProcessing.processString(vo.getCategoryNo()).length()/3 -1 ;
                return nodeFloors.contains(level);
            }).collect(Collectors.toList());
        }
        buildVoList(voList);
        return voList;
    }


    @Override
    public TreeVO categoryTreeVO(String parentCategoryNo, String categoryType, String[] checkedCategoryNos) {
        //构建树形结构有固定套路
        //1.确定根节点
        String root = StrUtil.isEmpty(parentCategoryNo) ? SuperConstant.ROOT_PARENT_ID : parentCategoryNo;
        //2.查询根节点下的所有子节点
        String head = NoProcessing.processString(root);
        //sql：select * from tab_category where category_no like ? and category_type = ?
        List<Category> list = this.lambdaQuery()
                .likeRight(Category::getCategoryNo, head)
                .eq(StrUtil.isNotBlank(categoryType), Category::getCategoryType, categoryType)
                .list();
        if (CollUtil.isEmpty(list)) {
            //说明没查到节点，前端给错了
            return TreeVO.builder().build();
        }
        //3.把节点之间的关系给挂上
        //3.1把CategoryList转换成树需要的TreeItemVOList
        List<TreeItemVO> treeItemVOList = list.stream().map(ca -> TreeItemVO.builder()
                        .id(ca.getCategoryNo())
                        .parentId(ca.getParentCategoryNo())
                        .label(ca.getCategoryName())
                        .build())
                .collect(Collectors.toList());
        //3.2挂关系
        //3.2.1把List集合转成Map，这个map的key是父ID，value是子节点的集合
        Map<String, List<TreeItemVO>> stringListMap = treeItemVOList.stream()
                .collect(Collectors.groupingBy(TreeItemVO::getParentId));
        //3.2.2遍历挂关系
        for (TreeItemVO treeItemVO : treeItemVOList) {
            treeItemVO.setChildren(stringListMap.get(treeItemVO.getId()));
        }
        //4.构建这个TreeVO，挂上根节点
        return TreeVO
                .builder()
                .items(stringListMap.get(root))
                .build();
    }

    @Override
    public String createCategoryNo(String parentCategoryNo) {
        CategoryVO categoryVO = CategoryVO.builder()
                .parentCategoryNo(parentCategoryNo)
                .build();
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Category::getParentCategoryNo, parentCategoryNo);
        List<Category> categoryList = list(queryWrapper);
        //无下属节点则创建下属节点
        if (EmptyUtil.isNullOrEmpty(categoryList)) {
            return NoProcessing.createNo(parentCategoryNo, false);
            //有下属节点则累加下属节点
        } else {
            Long categoryNo = categoryList.stream()
                    .map(category -> {
                        return Long.valueOf(category.getCategoryNo());
                    })
                    .max(Comparator.comparing(i -> i)).get();
            return NoProcessing.createNo(String.valueOf(categoryNo), true);
        }
    }

    /**
     * 人种榜险种榜分类
     *
     * @param type
     */
    @Override
    public List<CategoryVO> categoryCheckRule(String type) {
        //判断是否是险种榜
        if (InsureConstant.checkIsInsureType(type)) {
            List<CategoryVO> res = new ArrayList<>();
            //获取所有的险种榜
            List<String> allCheckRule = InsureConstant.getAllCheckRule();
            allCheckRule.forEach(e -> {
                CategoryVO categoryVO = CategoryVO.builder().categoryNo(e).categoryName(InsureConstant.getRuleNameById(e)).build();
                res.add(categoryVO);
            });
            return res;
        } else {
            //说明是人种榜
            List<String> categoryNames = Arrays.asList("成年人", "少儿", "老人");
            LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(Category::getCategoryName, categoryNames);
            queryWrapper.eq(Category::getDataState, SuperConstant.DATA_STATE_0);
            List<CategoryVO> res = BeanConv.toBeanList(list(queryWrapper), CategoryVO.class);
            return res;
        }
    }
}
